import os
import sys
import time
import paramiko
from influxdb import InfluxDBClient

#  从命令行获取ip，username，password参数
IP = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]

#  远程连接
def connectHost(ip, uname, passwd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, username=uname, password=passwd, port=22)
    return ssh


ssh = connectHost(IP, username, password)
stdin, stdout, stderr = ssh.exec_command('whoami')
ssh_name = stdout.readline().strip()
# print(ssh_name)

client = InfluxDBClient('localhost', 8086, 'root', '123456')
# get database
database_list = client.get_list_database()
# print(database_list)
for elem in database_list:
    if elem['name'] == ssh_name:
        client.drop_database(ssh_name)
        break

time.sleep(2)
client.create_database(ssh_name)
client.switch_database(ssh_name)

client.query(f'CREATE CONTINUOUS QUERY "cq_1m" ON "{ssh_name}" BEGIN '
             'SELECT mean("cpu_percent") AS "mean_cpu", '
             'mean("mem_percent") AS "mean_mem", '
             'mean("disk_percent") AS "mean_disk", '
             'mean("network_percent") AS "mean_network_percent" '
             'INTO "average_info" '
             'FROM "all_info" '
             'GROUP BY time(1m) '
             'END')

# 文件名称
local_path = os.getcwd()  # 读取当前目录
remote_path = '/home/' + ssh_name
name = 'ssh_monitor.py'

local_name = os.path.join(local_path, name)
remote_name = os.path.join(remote_path, name)

# if file exit or not
cmd = 'ls /home'
stdin, stdout, stderr = ssh.exec_command(cmd)
all_files = stdout.readlines()
all_files = [elem.strip() for elem in all_files]
if ssh_name not in all_files:
    cmd = f'mkdir {remote_path}'
    stdin, stdout, stderr = ssh.exec_command(cmd)
    print('create file success')



# 建立sftp连接
transport = paramiko.Transport((IP, 22))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)

# 上传文件
sftp.put(local_name, remote_name)
# 关闭连接
transport.close()

#  执行命令
cmd = 'which python3'
stdin, stdout, stderr = ssh.exec_command(cmd)
python3_path = stdout.readline().strip()

cmd = 'pip install psutil'
stdin, stdout, stderr = ssh.exec_command(cmd)

while True:
    cmd = '{0} {1}'.format(python3_path, remote_name)
    stdin, stdout, stderr = ssh.exec_command(cmd)
    # 读取信息
    line_list = stdout.readlines()
    text = line_list[0].strip()
    text = eval(text)
    client.write_points(text)
    time.sleep(5)

